package com.hanyxx.thread.lock;

import lombok.SneakyThrows;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo03 {
    public static void main(String[] args) throws InterruptedException {
        Demo03Service service = new Demo03Service();
        Demo03Thread t = new Demo03Thread(service);

        t.start();
        Thread.sleep(2000L);
        service.signal();
    }
}
class Demo03Service{
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
    //等待方法
    public void await() throws InterruptedException {
        lock.lock();
        System.out.println("await方法开始于：" + sdf.format(new Date(System.currentTimeMillis())));
        //该方法需在同步代码块中执行，否则会抛出IllegalMonitorStateException
        condition.await();
        System.out.println("await方法结束于：" + sdf.format(new Date(System.currentTimeMillis())));
        lock.unlock();
    }
    //通知方法
    public void signal() {
        lock.lock();
        System.out.println("signal方法开始于：" + sdf.format(new Date(System.currentTimeMillis())));
        condition.signal();
        lock.unlock();
    }
}
class Demo03Thread extends  Thread{
    private Demo03Service service;
    public Demo03Thread(Demo03Service service){
        this.service = service;
    }
    @SneakyThrows
    @Override
    public void run() {
        service.await();
    }
}
